<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>compile</h2>
      <p>a: {{ a }}</p>
      <p>b: {{ b }}</p>
    </div>

    <script>
      const str = document.querySelector("#app").innerHTML;
      const data = {
        a: 3,
        b: 4,
      };

      const compile = (node) => {
        node.innerHTML = str;
        // node.children可以得到这个元素的所有的子节点
        // console.log([...node.children]);
        const children = [...node.children];
        // 用正则去匹配是否有双大括号
        const reg = /\{\{(.*)\}\}/;

        children.forEach((child) => {
          // 检查每个子元素里面是否有双大括号，并且做替换
          if (reg.test(child.textContent)) {
            // 匹配到了以后，看双大括号里面的变量是什么，用data的属性去替换
            child.innerHTML = data[RegExp.$1.trim()];
          }
        });
      };

      compile(document.querySelector("#app"));

      const observer = (data, item, value) => {
        Object.defineProperty(data, item, {
          get() {
            // console.log(item + "被获取了");
            return value;
          },
          set(val) {
            // console.log(item + "被修改成了" + val);
            // console.log(item + "的值从" + value + "变成了" + val);
            value = val;
            compile(document.querySelector("#app"));
          },
        });
      };

      Object.keys(data).forEach((item) => {
        observer(data, item, data[item]);
      });

      setTimeout(() => {
        data.a = 30;
      }, 2000);

      setTimeout(() => {
        data.b = 40;
      }, 5000);
    </script>
  </body>
</html>
